package greentea.webloginmodule.servlets;

import java.io.*;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class LogoutHandler extends HttpServlet {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		// check if the session is logged in. If not - go to home page or login
		// page
		HttpSession session = req.getSession(false);
		if ((session == null)
				&& (session.getAttribute(LoginHandler.IS_LOGGED_IN) == null)) {
			// error because the logout should not be reached if it is not
			// logged in
			logger.error("Session not logged!!!");
			// goto main page or previous page
			req.getRequestDispatcher(LoginHandler.HOME_PAGE).forward(req, res);
			return;
		} else {
			// TODO do the JAAS logout
			LoginHandler.loginUtil.logout();

			logger.info("User ["
					+ (String) session.getAttribute(LoginHandler.IS_LOGGED_IN)
					+ "] logged out. Session ID:" + session.getId());

			// delete all attributes of the session
			Enumeration<String> attributes = session.getAttributeNames();
			while (attributes.hasMoreElements()) {
				session.removeAttribute(attributes.nextElement());
			}

			// kill the session
			session.invalidate();
			// forward to home page
			req.getRequestDispatcher(LoginHandler.HOME_PAGE).forward(req, res);
			return;
		}
	}

}